<template>
  <div class="page-container">
    <!-- 左侧筛选区域 -->
    <div class="filter-sidebar">
      <div class="filter-content" :class="{ collapsed: isCollapsed }">
        <el-form ref="queryRef" :inline="true" :model="state.queryForm" @keyup.enter="handleSearch">
          <!-- <el-form-item prop="job_status" label="实施时间">
            <el-date-picker
              v-model="datatimelist"
              type="daterange"
              style="width: 250px"
              range-separator="至"
              start-placeholder="开始日期"
              value-format="YYYY-MM-DD"
              end-placeholder="结束日期"
              @change="handleDateChange"
            />
          </el-form-item>
          <el-form-item prop="job_status" label="发布时间">
            <el-date-picker
              v-model="datatimelist1"
              style="width: 250px"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              value-format="YYYY-MM-DD"
              end-placeholder="结束日期"
              @change="handleDateChange1"
            />
          </el-form-item> -->
          <el-form-item label="关键词:" style="color: #4e5969">
            <el-input v-model="state.queryForm.likeStandardNameOrNo" placeholder="标准名称或编号"></el-input>
          </el-form-item>

          <el-form-item>
            <div class="" style="margin-left: 30px">
              <el-button icon="Search" type="primary" @click="handleSearch" color="#1890ff">查询</el-button>
              <el-button icon="RefreshRight" @click="handleReset" style="color: #4e5969">重置</el-button>
            </div>
          </el-form-item>
        </el-form>
        <!-- 标准等级筛选区域 -->

        <div
          class="filter-section"
          :style="{
            maxHeight: isExpanded ? '1000px' : '175px',
            // 60px 是默认一行的高度
          }"
        >
          <!-- <h4 class="filter-title">时间</h4> -->
          <div class="filter-options">
            <div class="filter-title mr10">实施日期</div>
            <div class="filter-div">
              <span class="filter-option" v-for="item in shishilist" :key="item.id" :class="{ active: selectedshishiid == item.id }" @click="selectshishi(item)">
                {{ item.name }}
              </span>
            </div>
          </div>
          <div class="filter-options">
            <div class="filter-title mr10">发布日期</div>
            <div class="filter-div">
              <span class="filter-option" v-for="item in fabulist" :key="item.id" :class="{ active: selectedfabuid == item.id }" @click="selectfabu(item)">
                {{ item.name }}
              </span>
            </div>
          </div>
          <div class="filter-options">
            <div class="filter-title mr10">标准等级</div>
            <div class="filter-div">
              <span class="filter-option" v-for="item in standardLevels" :key="item.id" :class="{ active: selectedLevelsid == item.id }" @click="selectbiaozhun(item)">
                {{ item.name }}
              </span>
            </div>
          </div>

          <div class="filter-options">
            <div class="filter-title mr10">标准状态</div>
            <div class="filter-div">
              <span class="filter-option" v-for="item in standardStatuses" :key="item.id" :class="{ active: selectedStatusesid == item.id }" @click="selectbzzt(item)">
                {{ item.name }}
              </span>
            </div>
          </div>

          <div class="filter-options">
            <div class="filter-title">基础分类</div>

            <div class="content">
              <FilterItem :data="categories" @update-selection="handleSelection" />
            </div>

            <!-- <FilterItem :parent-data="categories" @update-selection="handleSelection" /> -->
          </div>

          <div class="filter-options">
            <div class="filter-title">专题分类</div>

            <div class="content">
              <FilterItem :data="specialCategories" @update-selection="handleSelection1" />
            </div>
            <!-- <FilterItem :parent-data="specialCategories" @update-selection="handleSelection1" /> -->
          </div>
          <div class="filter-options">
            <div class="filter-title mr10">热门领域</div>
            <div class="filter-div">
              <span class="filter-option" v-for="item in hotlist" :key="item.id" :class="{ active: selectedhotid == item.id }" @click="selecthot(item)">
                {{ item.name }}
              </span>
            </div>
          </div>

          <div class="filter-options">
            <div class="filter-title mr10">建筑类型</div>
            <div class="filter-div">
              <span class="filter-option" v-for="item in jianzhulist" :key="item.id" :class="{ active: selectedjianzhuid == item.id }" @click="selectjianzhu(item)">
                {{ item.name }}
              </span>
            </div>
          </div>
          <div class="filter-options">
            <div class="filter-title mr10">工程专业分类</div>
            <div class="filter-div" style="width: 90%">
              <span class="filter-option" v-for="item in gongchenglist" :key="item.id" :class="{ active: selectedgongchengid == item.id }" @click="selectgongcheng(item)">
                {{ item.name }}
              </span>
            </div>
          </div>

          <div class="filter-options">
            <div class="filter-title mr10">工程生命周期分类</div>
            <div class="filter-div">
              <span class="filter-option" v-for="item in gongchengzhouqilist" :key="item.id" :class="{ active: selectedzhouqiid == item.id }" @click="selectzhouqi(item)">
                {{ item.name }}
              </span>
            </div>
          </div>
        </div>

        <div class="header" @click="toggleExpand">
          <div style="color: #4e5969">{{ isExpanded ? "收起" : "展开" }}</div>
          <img
            src="@/assets/imgs/xia1.png"
            :style="{
              width: '15px',
              height: '15px',
              transform: isExpanded ? 'rotate(180deg)' : 'rotate(0deg)',
              transition: 'transform 0.7s ease',
            }"
          />
        </div>
      </div>

      <!-- <div class="filter-footer">
        <el-button icon="Search" type="primary" @click="handleSearch">查询</el-button>

        <el-button icon="RefreshRight" @click="handleReset">重置</el-button>
      </div> -->
    </div>

    <!-- <tableList :dataList="tableData" :total="total"></tableList> -->
    <div class="table-main" style="margin-top: 20px">
      <el-table :data="tableData" stripe class="table-con">
        <el-table-column label="序号" type="index" fixed width="80" align="center" />
        <el-table-column prop="standardName" label="标准名称" align="center" />
        <el-table-column prop="standardNumber" label="标准编号" align="center" />
        <el-table-column prop="mainEditorUnitName" label="主编单位" align="center" />

        <el-table-column prop="publishTime" label="发布日期" align="center" />
        <el-table-column prop="implementTime" label="实施日期" align="center" />
      <el-table-column prop="" label="标准文件" align="center" width="90">
        <template #default="scope">
          <el-tooltip effect="dark" content="点击预览" placement="bottom" style="cursor: pointer">
            <el-icon size="18" @click="openwindow(scope.row)" style="cursor: pointer">
              <Document />
            </el-icon>
          </el-tooltip>
          &nbsp;&nbsp;&nbsp;
          <el-tooltip effect="dark" content="点击下载" placement="bottom" style="cursor: pointer">
            <el-icon size="18" @click="downloadFile(scope.row )" style="cursor: pointer">
              <Download />
            </el-icon>
          </el-tooltip>
        </template>
      </el-table-column>

        <el-table-column label="操作" header-align="center" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="detailRecord(scope.row)">详细信息</el-button>
          </template>
        </el-table-column>

      </el-table>
      <div class="pagination-content">
        <el-config-provider :locale="zhCn">
          <el-pagination
            v-model:current-page="state.pageNum"
            v-model:page-size="state.pageSize"
            :page-sizes="[10, 20, 30, 100]"
            background
            layout="sizes, prev, pager, next, jumper"
            :total="state.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-config-provider>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import axios from "axios";
  import { ElMessage } from "element-plus";
  import { computed, onMounted, reactive, ref } from "vue";
  const isCollapsed = ref(false);
  import FilterItem from "./FilterItem.vue";
  import { getServerUrl } from "@/utils/url";
    import CryptoJS from "crypto-js";
  import { useRouter } from "vue-router";
  const router = useRouter();
  // import { useDictionaryStore } from '@/stores/dictionary'
  // const dictionaryStore = useDictionaryStore()
  const serverUrl = getServerUrl();
  // 关键词搜索
  const selectedKeywordType = ref("");
  const searchKeyword = ref("");

  let pid = ref("");
  const state = reactive({
    queryForm: {
      likeStandardNameOrNo: "", //标准名称或编号
      startImplementTime: "", //实施时间(开始)
      endImplementTime: "", //实施时间(结束)
      startPublishTime: "", //发布时间(开始)
      endPublishTime: "", //发布时间(结束)
      labels: [], //字段内容与查询、详情接口相同,建议复用,hasChosen=true视为选择
      basicCategories: [],
      specialCategories: [],
    },
    pageNum: 1,
    pageSize: 10,
    total: 1,
    dataListLoading: false,
    keyType: "",
    keyword: null,
  });
  const datatimelist = ref([]);
  const datatimelist1 = ref([]);
  const handleDateChange = (val: any) => {
    console.log("日期范围选择器的值:", val);
    datatimelist.value = val || [];
    state.queryForm.startImplementTime = val[0] ? val[0] : "";
    state.queryForm.endImplementTime = val[1] ? val[1] : "";
  };
  const handleDateChange1 = (val: any) => {
    console.log("日期范围选择器的值:", val);
    state.queryForm.startPublishTime = val[0] ? val[0] : "";
    state.queryForm.endPublishTime = val[1] ? val[1] : "";
    datatimelist1.value = val || [];
  };

  interface StandardLevel {
    id: string;
    type: number;
    name: string;
    weight: number;
    remark: string | null;
  }
  const topLevelStandards = computed(() => categories.value.filter(item => item.pid === "0"));
  // 标准等级数据
  const standardLevels = ref<StandardLevel[]>([]);
  const selectedLevels = ref<StandardLevel[]>([]);

  // 标准状态数据
  const standardStatuses = ref<StandardLevel[]>([]);
  const selectedStatuses = ref<StandardLevel[]>([]);
  const selectedgongchengzhouqi = ref<StandardLevel[]>([]);
  const selectedjianzhu = ref<StandardLevel[]>([]);
  const selectedgongcheng = ref<StandardLevel[]>([]);
  const selectedhot = ref<StandardLevel[]>([]);
  const selectedfabu = ref<StandardLevel[]>([]);
  const selectedshishi = ref<StandardLevel[]>([]);

  const shishilist = ref<StandardLevel[]>([]);
  const fabulist = ref<StandardLevel[]>([]);
  const hotlist = ref<StandardLevel[]>([]);
  const jianzhulist = ref<StandardLevel[]>([]);
  const gongchenglist = ref<StandardLevel[]>([]);
  const gongchengzhouqilist = ref<StandardLevel[]>([]);

  // 分类数据
  const categories = ref([]);
  const specialCategories = ref([]);

  const selectedCategories = ref<string[]>([]);

  const categoryExpanded = ref<Record<string, boolean>>({
    urban: true,
    urbanBasic: false,
    geotechnical: false,
    municipal: false,
    construction: false,
    application: false,
  });
  const toggleCategoryExpand = (value: string) => {
    categoryExpanded.value[value] = !categoryExpanded.value[value];
  };

  const checklabels = ref([]);
  const checklabels1 = ref([]);
  const isExpanded = ref(false);
  const toggleExpand = () => {
    isExpanded.value = !isExpanded.value;
  };
  const isExpanded1 = ref(false);
  const toggleExpand1 = () => {
    isExpanded1.value = !isExpanded1.value;
  };

  const handleSelection = (payload: { id: string }) => {
    checklabels.value = [];
    checklabels.value.push(payload.id);
    getDataList();
  };

  const handleSelection1 = (payload: { id: string }) => {
    checklabels1.value = [];
    checklabels1.value.push(payload.id);
    getDataList();
  };

  const detailRecord = (row: any) => {
    router.push({ name: "detailRecord", params: { id: row.id } });
  };

  // 3. 处理子组件的切换事件（控制展开/折叠+关闭同级）
  const handleToggle = (currentItem: FilterItemType, parentItem?: FilterItemType) => {
    // 切换当前项的展开状态
    currentItem.expanded = !currentItem.expanded;

    // 关闭同级其他项（避免多个同级同时展开）
    if (parentItem?.children) {
      parentItem.children.forEach(sibling => {
        if (sibling.id !== currentItem.id) {
          sibling.expanded = false;
          // 递归关闭子级的子级
          closeAllDescendants(sibling);
        }
      });
    }
  };

  // 4. 递归关闭所有后代子级
  const closeAllDescendants = (item: FilterItemType) => {
    if (item.children && item.children.length > 0) {
      item.children.forEach(child => {
        child.expanded = false;
        closeAllDescendants(child);
      });
    }
  };
  // 时间筛选
  const timeOptions = [
    { value: "week", label: "近一周" },
    { value: "month", label: "近一个月" },
    { value: "quarter", label: "近三个月" },
    { value: "halfyear", label: "近半年" },
    { value: "year", label: "近一年" },
    { value: "custom", label: "自定义" },
  ];
  const selectedTime = ref("week");
  const startDate = ref("");
  const endDate = ref("");
  const removeItemByName = (name: string) => {
    const index = labels.value.findIndex(item => item.typeName === name);
    if (index !== -1) {
      labels.value.splice(index, 1);
    }
  };
  const selectTime = (value: string) => {
    selectedTime.value = value;
    if (value !== "custom") {
      startDate.value = "";
      endDate.value = "";
    }
  };
  const selectedLevelsid = ref(null);
  const selectbiaozhun = (item: StandardLevel) => {
    //  selectedLevels.value = [value];
    // const index = selectedLevelsid.value.indexOf(item.id);
    const index = selectedLevels.value.findIndex(selected => selected.id === item.id);
    if (index === -1) {
      selectedLevels.value = [];
      selectedLevelsid.value = item.id;
      selectedLevels.value.push(item); // 选中
      removeItemByName("标准（类别）等级标签");
      const aa = {
        type: "1",
        typeName: "标准（类别）等级标签",
        options: selectedLevels.value,
      };
      labels.value.push(aa);
    } else {
      selectedLevelsid.value = null;
      selectedLevels.value = []; // 取消选中
      removeItemByName("标准（类别）等级标签");
    }

    handleSearch();
  };

  const selectedshishiid = ref(null);
  const selectshishi = (item: StandardLevel) => {
    //  selectedLevels.value = [value];
    // const index = selectedshishiid.value.indexOf(item.id);
    const index = selectedshishi.value.findIndex(selected => selected.id === item.id);
    if (index === -1) {
      selectedshishi.value = [];
      removeItemByName("实施日期分类");
      selectedshishiid.value = item.id;
      selectedshishi.value.push(item); // 选中
      const aa = {
        type: "16",
        typeName: "实施日期分类",
        options: selectedshishi.value,
      };
      labels.value.push(aa);
    } else {
      selectedshishiid.value = null;
      selectedshishi.value = []; // 取消选中
      removeItemByName("实施日期分类");
    }

    handleSearch();
  };

  const selectedfabuid = ref(null);
  const selectfabu = (item: StandardLevel) => {
    //  selectedLevels.value = [value];
    const index = selectedfabu.value.findIndex(selected => selected.id === item.id);
    if (index === -1) {
      selectedfabuid.value = item.id;
      removeItemByName("发布日期分类");
      selectedfabu.value = [];
      selectedfabu.value.push(item); // 选中
      const aa = {
        type: "15",
        typeName: "发布日期分类",
        options: selectedfabu.value,
      };
      labels.value.push(aa);
    } else {
      selectedfabuid.value = null;
      selectedfabu.value = []; // 取消选中
      removeItemByName("发布日期分类");
    }

    handleSearch();
  };

  const selectedhotid = ref(null);
  const selecthot = (item: StandardLevel) => {
    //  selectedLevels.value = [value];
    const index = selectedhot.value.findIndex(selected => selected.id === item.id);
    if (index === -1) {
      selectedhotid.value = item.id;
      removeItemByName("热门领域标签");
      selectedhot.value = [];
      selectedhot.value.push(item); // 选中
      const aa = {
        type: "13",
        typeName: "热门领域标签",
        options: selectedhot.value,
      };
      labels.value.push(aa);
    } else {
      selectedhotid.value = null;
      selectedhot.value = []; // 取消选中
      removeItemByName("热门领域标签");
    }

    handleSearch();
  };
  const selectedjianzhuid = ref();
  const selectjianzhu = (item: StandardLevel) => {
    //  selectedLevels.value = [value];
    const index = selectedjianzhu.value.findIndex(selected => selected.id === item.id);
    if (index === -1) {
      selectedjianzhuid.value = item.id;
      removeItemByName("工建筑类型分类");
      selectedjianzhu.value = [];
      selectedjianzhu.value.push(item); // 选中
      const aa = {
        type: "6",
        typeName: "工建筑类型分类",
        options: selectedjianzhu.value,
      };
      labels.value.push(aa);
    } else {
      selectedjianzhuid.value = null;
      selectedjianzhu.value = []; // 取消选中
      removeItemByName("工建筑类型分类");
    }

    handleSearch();
  };

  const selectedgongchengid = ref();
  const selectgongcheng = (item: StandardLevel) => {
    //  selectedLevels.value = [value];
    const index = selectedgongcheng.value.findIndex(selected => selected.id === item.id);
    if (index === -1) {
      selectedgongchengid.value = item.id;
      selectedgongcheng.value = [];
      removeItemByName("工程专业分类");
      selectedgongcheng.value.push(item); // 选中
      const aa = {
        type: "7",
        typeName: "工程专业分类",
        options: selectedgongcheng.value,
      };
      labels.value.push(aa);
    } else {
      selectedgongchengid.value = null;
      selectedgongcheng.value = []; // 取消选中
      removeItemByName("工程专业分类");
    }

    handleSearch();
  };

  const selectedzhouqiid = ref(null);
  const selectzhouqi = (item: StandardLevel) => {
    //  selectedLevels.value = [value];
    const index = selectedgongchengzhouqi.value.findIndex(selected => selected.id === item.id);
    if (index === -1) {
      selectedzhouqiid.value = item.id;
      removeItemByName("工程全生命周期分类");
      selectedgongchengzhouqi.value = [];
      selectedgongchengzhouqi.value.push(item); // 选中

      const aa = {
        type: "5",
        typeName: "工程全生命周期分类",
        options: selectedgongchengzhouqi.value,
      };
      labels.value.push(aa);
    } else {
      selectedzhouqiid.value = null;
      selectedgongchengzhouqi.value = []; // 取消选中
      removeItemByName("工程全生命周期分类");
    }

    handleSearch();
  };

  const selectedStatusesid = ref();
  const selectbzzt = (item: StandardLevel) => {
    const index = selectedgongchengzhouqi.value.findIndex(selected => selected.id === item.id);
    if (index === -1) {
      selectedStatusesid.value = item.id;
      removeItemByName("标准（类别）状态标签");
      selectedStatuses.value = [];
      selectedStatuses.value.push(item); // 选中
      const aa = {
        type: "2",
        typeName: "标准（类别）状态标签",
        options: selectedStatuses.value,
      };
      labels.value.push(aa);
    } else {
      selectedStatusesid.value = null;
      selectedStatuses.value = []; // 取消选中
      removeItemByName("标准（类别）状态标签");
    }
    handleSearch();
  };
  const handleSearch = () => {
   // console.log("搜索:", selectedKeywordType.value, searchKeyword.value);
    state.pageNum = 1;
    state.pageSize = 10;
    state.total = 0;
    state.dataListLoading = false;
    getDataList();
  };

  const handleSizeChange = (val: number) => {
    state.pageSize = val;
    getDataList();
  };
  const handleCurrentChange = (val: number) => {
    state.pageNum = val;
    getDataList();
  };
  const handleReset = () => {
    state.queryForm.labels = [];
    state.queryForm.basicCategories = [];
    state.queryForm.specialCategories = [];
    state.queryForm.startImplementTime = "";
    state.queryForm.endImplementTime = "";
    state.queryForm.startPublishTime = "";
    state.queryForm.endPublishTime = "";
    state.queryForm.likeStandardNameOrNo = "";
    state.pageNum = 1;
    state.pageSize = 10;
    state.total = 0;
    state.dataListLoading = false;
    state.keyType = "";
    state.keyword = null;
    checklabels.value = [];
    checklabels1.value = [];
    datatimelist.value = [];
    datatimelist1.value = [];
    selectedshishiid.value = [];
    selectedshishi.value = [];
    selectedfabuid.value = [];
    selectedfabu.value = [];
    selectedLevelsid.value = [];
    selectedLevels.value = [];
    selectedfabuid.value = [];
    selectedfabu.value = [];
    selectedhotid.value = [];
    selectedhot.value = [];
    selectedjianzhuid.value = [];
    selectedjianzhu.value = [];
    selectedgongchengid.value = [];
    selectedgongcheng.value = [];
    selectedzhouqiid.value = [];
    selectedgongchengzhouqi.value = [];
    selectedStatusesid.value = [];
    selectedStatuses.value = [];
    labels.value = [];
    tableData.value = [];
    getDataList();
  };

  interface dictionaryModel {
    category: string;
    code: string;
    createBy: string;
    createTime: string;
    id: string;
    iflag: number;
    isTreelist: number;
    name: string;
    parentCode: string;
    parentId: string;
    remark: string;
    theOrder: number;
    treeLevel: number;
    updateBy: string;
    updateTime: string;
  }
  onMounted(() => {
    getDataList();
    initCategory();
    queryOnWeb();
  });

  const dictionaryList = ref<DictionaryItem[]>([]);

  const getDictionaryByCode = computed(() => {
    return (code: string) => {
      if (!Array.isArray(dictionaryList.value)) {
        console.warn("dictionaryList.value is not an array");
        return [];
      }
      return dictionaryList.value.filter(val => val.code === code).sort((a, b) => a.theOrder - b.theOrder);
    };
  });

  const getDictionaryBytype = computed(() => {
    return (code: string) => {
      if (!Array.isArray(dictionaryList.value)) {
        console.warn("dictionaryList.value is not an array");
        return [];
      }
      return dictionaryList.value.filter(val => val.code === code).sort((a, b) => a.theOrder - b.theOrder);
    };
  });
  const emit = defineEmits(["updateArray"]);
  const tableData = ref([]);
  const total = ref(0);

  const handleRefresh = () => {
    console.log("刷新表格数据");
  };

  const initData = async (data: any) => {
    const respon = await axios.post(serverUrl + "standardSystem/extraStatistic", data);
    if (respon.data.data) {
      emit("updateArray", respon.data.data); // 触发事件并传递数据
    } else {
      ElMessage.error(respon.data.msg);
    }
  };
  const labels = ref([]);
  const getDataList = async () => {
    state.dataListLoading = true;
    //  let label = [
    //   {
    //     type: "1",
    //     typeName: "标准（类别）等级标签",
    //     options: selectedLevels.value,
    //   },
    //   {
    //     type: "2",
    //     typeName: "标准（类别）状态标签",
    //     options: selectedStatuses.value,
    //   },
    //   {
    //     type: "5",
    //     typeName: "工程全生命周期分类",
    //     options: selectedgongchengzhouqi.value,
    //   },

    //   {
    //     type: "6",
    //     typeName: "工建筑类型分类",
    //     options: selectedjianzhu.value,
    //   },
    //   {
    //     type: "7",
    //     typeName: "工程专业分类",
    //     options: selectedgongcheng.value,
    //   },
    //   {
    //     type: "13",
    //     typeName: "热门领域标签",
    //     options: selectedhot.value,
    //   },
    //   {
    //     type: "15",
    //     typeName: "发布日期分类",
    //     options: selectedfabu.value,
    //   },
    //   {
    //     type: "16",
    //     typeName: "实施日期分类",
    //     options: selectedshishi.value,
    //   },

    // ];

    try {
      const response = await axios.post(serverUrl + "standardSystem/extraList", {
        likeStandardNameOrNo: state.queryForm.likeStandardNameOrNo,
        startImplementTime: state.queryForm.startImplementTime,
        endImplementTime: state.queryForm.endImplementTime,
        startPublishTime: state.queryForm.startPublishTime,
        endPublishTime: state.queryForm.endPublishTime,
        labels: labels.value,
        basicCategories: checklabels.value,
        specialCategories: checklabels1.value,
        pageNum: state.pageNum,
        pageSize: state.pageSize,
      });
      tableData.value = response.data.data.list;
      total.value = response.data.data.total;
      const data = {
        likeStandardNameOrNo: state.queryForm.likeStandardNameOrNo,
        startImplementTime: state.queryForm.startImplementTime,
        endImplementTime: state.queryForm.endImplementTime,
        startPublishTime: state.queryForm.startPublishTime,
        endPublishTime: state.queryForm.endPublishTime,
        labels: labels.value,
        basicCategories: checklabels.value,
        specialCategories: checklabels1.value,
      };
      initData(data);
    } catch (error) {
      console.error("数据加载失败:", error);
    }
  };

  interface OptionItem {
    typeName: string;
    options: any[]; // 如果 options 的结构已知，可以进一步定义具体类型
  }

  const labelsArr = (name: string, arrList: OptionItem[]) => {
    let retArr: any[] = []; // 如果返回值类型已知，可以替换为具体类型
    arrList.forEach((item: OptionItem) => {
      if (item.typeName === name) {
        retArr = item.options;
      }
    });
    return retArr;
  };
  const initCategory = async () => {
    // 分类字典
    const dataForm = {};
    const response = await axios.get(serverUrl + "standardSystem/listCategoryAndLabel", { params: dataForm });
    standardLevels.value = labelsArr("标准（类别）等级标签", response.data.data.labels);
    standardStatuses.value = labelsArr("标准状态", response.data.data.labels);
    shishilist.value = labelsArr("实施日期分类", response.data.data.labels);
    fabulist.value = labelsArr("发布日期分类", response.data.data.labels);
    hotlist.value = labelsArr("热门领域标签", response.data.data.labels);
    jianzhulist.value = labelsArr("建筑类型分类", response.data.data.labels);
    gongchenglist.value = labelsArr("工程专业分类", response.data.data.labels);
    gongchengzhouqilist.value = labelsArr("工程全生命周期分类", response.data.data.labels);
    categories.value = response.data.data.basicCategories;
    specialCategories.value = response.data.data.specialCategories;
  };

  const queryOnWeb = async () => {
    const response = await axios.post(serverUrl + "api/standardDictionary/queryOnWeb", {
      parentId: "",
      isTreelist: 1,
      category: "",
      code: "",
      name: "",
      parentCode: "",
      treeLevel: 1,
      pageIndex: 1,
      pageSize: 1000,
    });
    dictionaryList.value = response.data.data.list;
  };

  const filterData = ref([]);
  const topLevelItems = computed(() => filterData.value.filter(item => item.pid === "0"));

  // 响应式状态
  const selectedIds = ref<(string | number)[]>([]);
  const expandedIds = ref<(string | number)[]>([]);

  // 按深度组织层级数据（0:第一层级, 1:第二层级, 2:第三层级...）

  // 处理展开/折叠
  const handleToggleExpand = (id: string | number) => {
    if (expandedIds.value.includes(id)) {
      expandedIds.value = expandedIds.value.filter(itemId => itemId !== id);
    } else {
      expandedIds.value.push(id);
    }
  };

  // 处理选中状态
  const handleToggleSelect = (payload: { ids: (string | number)[]; isSelect: boolean }) => {
    if (payload.isSelect) {
      // 选中：添加ID（去重）
      selectedIds.value = [...new Set([...selectedIds.value, ...payload.ids])];
    } else {
      // 取消选中：移除ID
      selectedIds.value = selectedIds.value.filter(id => !payload.ids.includes(id));
    }
  };

  const totalClick = (id: any, val: any) => {
    const response = axios.get(`${serverUrl}external/localStandard/viewDownloadCount`, {
      params: {
        progressId: val,
        countType: id,
      },
    });
  };
    const openwindow = async (value: any) => {
    let valueid = null;

      valueid = value.fileId;


    if (valueid) {
    //  totalClick(1, value.progressId);
      const timestamp = Date.now();
      const secretKey = "jkysh2jgbstandard";
      // 生成receivedToken
      const receivedToken = CryptoJS.HmacSHA256(valueid + ":" + timestamp, secretKey).toString(CryptoJS.enc.Hex);
      try {
        const response = await axios.get(`${serverUrl}api/files/webPreview`, {
          params: {
            fileId: valueid,
            timestamp: timestamp,
            receivedToken: receivedToken,
          },
        });

        if (!response.data.data) {
          ElMessage.error("文件不存在或数据无效");
        } else if (response.data.data.url) {
          window.open(response.data.data.url, "_blank");
        } else {
          ElMessage.error("文件预览失败: 未返回有效的预览URL");
        }
      } catch (error) {
        if (error.response) {
          const errorData = error.response.data;
          ElMessage.error(errorData.message || "文件预览失败");
        } else {
          ElMessage.error("网络异常，请稍后重试");
        }
      }
    }
  };
  const downloadFile = async (value: any) => {
    let valueid = null;
  
      valueid = value.fileId;
 
    if (valueid) {
    //  totalClick(2, value.progressId);
      const timestamp = Date.now();
      const secretKey = "jkysh2jgbstandard";
      // 生成receivedToken
      const receivedToken = CryptoJS.HmacSHA256(valueid + ":" + timestamp, secretKey).toString(CryptoJS.enc.Hex);
      try {
        const response = await axios.get(serverUrl + "api/files/webDownload", {
          params: {
            // 修正：GET 请求参数应放在 `params` 中
            fileId: valueid,
            timestamp: timestamp,
            receivedToken: receivedToken,
          },

          responseType: "blob",
        });

        // 从响应头中提取文件名和文件类型

        const contentDisposition = response.headers["content-disposition"] || response.headers["Content-Disposition"];
        const contentType = response.headers["content-type"];

        // 默认文件名和文件类型
        let fileName = getFileNameFromContentDisposition(contentDisposition) || "default-filename";
        let fileExtension = "bin"; // 默认扩展名

        // 提取文件名
        // if (contentDisposition) {
        //     const match = contentDisposition.match(/filename="?(.+)"?/);
        //     if (match && match[1]) {
        //         fileName = match[1];
        //     }
        // }

        // 提取文件扩展名（根据 Content-Type）
        if (contentType) {
          const extensionMap: Record<string, string> = {
            "application/pdf": "pdf",
            "application/msword": "doc",
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
            "application/vnd.ms-excel": "xls",
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
            "image/jpeg": "jpg",
            "image/png": "png",
            "text/plain": "txt",
          };
          fileExtension = extensionMap[contentType] || fileExtension;
        }

        // 确保文件名包含正确的扩展名
        if (!fileName.includes(".")) {
          fileName = `${fileName}.${fileExtension}`;
        }

        // 创建 Blob 对象并生成下载链接
        const blob = new Blob([response.data]);
        const downloadUrl = window.URL.createObjectURL(blob);

        // 创建 <a> 标签并触发下载
        const a = document.createElement("a");
        a.href = downloadUrl;
        a.download = fileName; // 使用动态生成的文件名
        document.body.appendChild(a);
        a.click();

        // 清理资源
        document.body.removeChild(a);
        window.URL.revokeObjectURL(downloadUrl);
      } catch (error) {
        console.error("文件下载失败：", error);
      }
    } else {
      ElMessage.error("暂无文件");
    }
  };
  const getFileNameFromContentDisposition = (contentDisposition: string) => {
    if (!contentDisposition) return null;

    // 处理标准文件名（filename="..."）
    const filenameMatch = contentDisposition.match(/filename="?(.+?)"?(;|$)/i);
    if (filenameMatch && filenameMatch[1]) {
      return decodeURIComponent(filenameMatch[1]); // 解码 URL 编码
    }

    // 处理 RFC 5987 编码的文件名（filename*=UTF-8''...）
    const filenameStarMatch = contentDisposition.match(/filename\*=UTF-8''(.+?)(;|$)/i);
    if (filenameStarMatch && filenameStarMatch[1]) {
      return decodeURIComponent(filenameStarMatch[1]); // 解码 URL 编码
    }

    return null; // 未找到文件名
  };
</script>
<style>
.table-con th {
  height: 50px;
  /* 自定义表头高度 */
  line-height: 50px;
  color: #333;
  /* 确保文字垂直居中 */
  background-color: #cecece !important;
  /* 自定义背景色 */
}

.table-con .el-table__row--striped {
  background-color: #eee;
}

.table-con .cell {
  padding: 0 8px !important;
}

.table-con .el-table__cell {
  padding: 6px 0 !important;
}

.table-con .el-table__row {
  height: 45px;
  /* 自定义行高 */
}
</style>
<style scoped>
.expandable-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.filter-div {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  gap: 8px;
  height: 100%;
}

.ml10 {
  margin-left: 10px;
}

.mr10 {
  margin-right: 10px;
}

.header {
  padding: 4px 5px;
  cursor: pointer;
  display: flex;
  flex-direction: row;
  align-items: center;
}

.content {
  flex: 1;
  overflow: hidden;
  transition: max-height 0.3s ease, opacity 0.3s ease;
  /* 同时动画高度和透明度 */
}

.top-level {
  gap: 10px;
  display: flex;
  flex-flow: wrap;
  overflow: hidden;
  position: relative;
}

.filter-footer {
  display: flex;
  justify-content: center;
  padding: 10px;
  margin-bottom: 20px;
}

.table-main {
  display: flex;
  flex-direction: column;
  gap: 10px;
  flex: 1;
  align-items: center;
}

.el-form--inline .el-form-item {
  display: inline-flex;
  margin-right: 22px;
  vertical-align: middle;
}

.page-container {
  display: flex;
  height: 100%;

  /* overflow: auto; */
  flex-direction: column;
}

.filter-sidebar {
  border: 1px solid #e5e6eb;
  width: 100%;
  background-color: #ffffff;

  transition: width 0.3s ease;
  box-shadow: 2px 0 5px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
}

.filter-header {
  padding: 16px 20px;
  border-bottom: 1px solid #e5e6eb;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-header h3 {
  margin: 0;
  font-size: 16px;
  color: #1d2129;
  font-weight: 600;
}

.collapse-btn {
  background: none;
  border: none;
  color: #86909c;
  cursor: pointer;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.collapse-btn:hover {
  background-color: #f2f3f5;
  color: #1d2129;
}

.filter-content {
  padding: 20px;
  /* overflow-y: auto; */
  flex: 1;
}

.filter-sidebar.collapsed {
  width: 60px;
}

.filter-content.collapsed {
  padding: 10px 0;
}

.filter-content.collapsed .filter-section {
  display: none;
}

.filter-section {
  overflow: hidden;
  margin-bottom: 14px;
  transition: max-height 1s ease;
}

.filter-title {
  font-size: 14px;
  color: #fff;
  font-weight: 500;
  display: flex;
  align-items: center;
  border-radius: 50px;
  /* background-color: #1890ff; */
  padding: 4px 12px;
  background: linear-gradient(to bottom, #65aef7, #1890ff);
  /* 从橙色到浅橙色的渐变 */

  /* line-height: 30px; */
}

.keyword-filter {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
}

.keyword-label {
  color: #4e5969;
  font-size: 14px;
  white-space: nowrap;
}

.keyword-select,
.keyword-input {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.2s;
}

.keyword-select:focus,
.keyword-input:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.search-group {
  display: flex;
  flex: 1;
  min-width: 120px;
}

.keyword-input {
  flex: 1;
  border-right: none;
  border-radius: 4px 0 0 4px;
}

.search-btn {
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-left: none;
  border-radius: 0 4px 4px 0;
  padding: 0 12px;
  color: #86909c;
  cursor: pointer;
  transition: all 0.2s;
}

.search-btn:hover {
  background-color: #e9ecef;
  color: #1d2129;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.query-btn,
.reset-btn {
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
}

.query-btn {
  background-color: #1890ff;
  color: #ffffff;
  border: 1px solid #1890ff;
}

.query-btn:hover {
  background-color: #096dd9;
  border-color: #096dd9;
}

.reset-btn {
  background-color: #ffffff;
  color: #1890ff;
  border: 1px solid #1890ff;
}

.reset-btn:hover {
  background-color: #f0f7ff;
}

.filter-options {
  display: flex;
  width: 100%;
  /* gap: 8px; */
  margin-bottom: 18px;
  position: relative;
  flex-direction: row;
  align-items: flex-start;
}

.filter-option {
  padding: 4px 12px;
  /* border-radius: 16px;
    border: 1px solid #dcdfe6; */
  font-size: 13px;
  cursor: pointer;

  transition: all 0.2s;

  color: #4e5969;
  white-space: nowrap;
}

.filter-option:hover {
  border-color: #1890ff;
  color: #1890ff;
  background-color: #f0f7ff;
  border-radius: 16px;
}

.filter-option.active {
  background-color: #e6f7ff;
  color: #1890ff;
  border-color: #91d5ff;
  border-radius: 16px;
}

.count {
  color: #86909c;
  font-size: 12px;
}

.custom-time {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 12px;
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.date-input {
  padding: 6px 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 13px;
}

.date-separator {
  color: #86909c;
}

.table-container {
  flex: 1;
  padding: 20px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.table-header h3 {
  margin: 0;
  font-size: 18px;
  color: #1d2129;
}

.table-actions {
  display: flex;
  gap: 12px;
}

.btn-export,
.btn-refresh {
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 6px;
  border: 1px solid #dcdfe6;
  background-color: #ffffff;
  color: #4e5969;
}

.btn-export:hover,
.btn-refresh:hover {
  border-color: #1890ff;
  color: #1890ff;
  background-color: #f0f7ff;
}

.table-content {
  background-color: #ffffff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  flex: 1;
  overflow: auto;
}

.table-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #86909c;
  padding: 20px;
  text-align: center;
}

.filter-info {
  margin-top: 12px;
  font-size: 13px;
  max-width: 80%;
  word-break: break-word;
}

@media (max-width: 768px) {
  .page-container {
    flex-direction: column;
  }

  .filter-sidebar {
    width: 100%;
    border-right: none;
    border-bottom: 1px solid #e5e6eb;
  }

  .keyword-filter {
    flex-direction: column;
    align-items: stretch;
  }

  .keyword-label {
    margin-bottom: 4px;
  }

  .action-buttons {
    width: 100%;
    justify-content: flex-end;
  }
}

.hide {
  display: none !important;
}

.show {
  display: block !important;
}

.filter-category-group {
  margin-bottom: 8px;
}

.filter-category {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid #dcdfe6;
  color: #4e5969;
  white-space: nowrap;
}

.filter-category:hover {
  border-color: #1890ff;
  color: #1890ff;
  background-color: #f0f7ff;
}

.sub-categories {
  margin-left: 16px;
}

.sub-category {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid #dcdfe6;
  color: #4e5969;
  white-space: nowrap;
}

.sub-category:hover {
  border-color: #1890ff;
  color: #1890ff;
  background-color: #f0f7ff;
}

.sub-sub-categories {
  margin-left: 16px;
}

.sub-sub-category {
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid #dcdfe6;
  color: #4e5969;
  white-space: nowrap;
}

.sub-sub-category:hover {
  border-color: #1890ff;
  color: #1890ff;
  background-color: #f0f7ff;
}

.sub-sub-category.active {
  background-color: #e6f7ff;
  color: #1890ff;
  border-color: #91d5ff;
}
</style>
